#include <fstream>
#include <inttypes.h>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include "logger.h"

using namespace std;

class gnuplotScript
{
public:
	gnuplotScript();
	~gnuplotScript();

	bool openFile();
	void writeScript();
	void writeHeader();
	void writeLog(int);
	string points();


	fstream	file;
	bool 	usePoints;
	bool 	doExport;
	bool	disableKey;
	bool	coalesceLogs;
	int		colNum;

	vector<analyzerResultList>	miscLines;
	vector<analyzerResultList>	fullResultList;

	string outputFile;
	string title;
	
	string graphTitle;
	string xLabel;
	string yLabel;
};

gnuplotScript::gnuplotScript()
{
	usePoints=false;
	doExport=false;
	disableKey=false;
	colNum=0;

	outputFile	= "";
	title		= "";
	graphTitle 	= "";
	xLabel 		= "";
	yLabel 		= "";
}

gnuplotScript::~gnuplotScript()
{
	if (file.is_open())
		file.close();
}

bool gnuplotScript::openFile()
{
	if (file.is_open())
		return true;

	file.open("auto.p", ios::out);

	if (!file.is_open())
		return false;
	return true;
}

void gnuplotScript::writeHeader()
{
	if (!openFile())	return;
	file << "set autoscale\nunset log\nunset label\nset xtic auto\nset ytic auto\n";

	if (doExport)
		file << "set term svg size 925 625\nset output \"graph.svg\"\n";
	
	if (disableKey)
		file << "set key off\n";
		
	if(graphTitle.size() > 0)
		file << "set title \"" << graphTitle << "\"\n";

	if(xLabel.size() > 0)
		file << "set xlabel \"" << xLabel << "\"\n";
		
	if(yLabel.size() > 0)
		file << "set ylabel \"" << yLabel << "\"\n";
}

void gnuplotScript::writeScript()
{
	if (!openFile())			return;

	colNum = 0;

	writeHeader();

	for (uint i = 0; i < fullResultList.size(); i++)
	{
		title = fullResultList[i].filename;
		int logNum = fullResultList[i].sessionNumber;
		INFO("Writing log number " << logNum << "; Filename: " << title)

		// Only the VERY first session gets the 'plot' word.
		if (i == 0)								file << "plot \"";
		else									file << "\t\t\"";

		// Print out the meat...
		file << outputFile << "\" using 1:" << 2 + colNum++
			<< " title \'" << title << "_" << logNum
			<< "\' with " << points();

		// All sessions but the VERY last session gets ' , \\'
		// This means that if there is EXACTLY one session, ',\\' never gets
		// printed out to file.
		if (i != fullResultList.size() -1)
			file << " , \\\n";
	}

	// --- Print out miscellaneous lines ---
	for (uint line = 0; line < miscLines.size(); line++)
		for(uint point = 0; point < miscLines[line].size(); point++)
		{
			file << " , \\\n" << "\t\t" << miscLines[line][point]; 
		}	
}

string gnuplotScript::points()
{
	if (usePoints)	return "linespoints";
	else 			return "lines";
}
